package com.spark.lola.hander;

import com.alibaba.fastjson.JSON;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.netty.annotation.HawkBean;
import com.spark.lola.support.netty.annotation.HawkMethod;
import com.spark.lola.support.netty.api.NettyPermissionService;
import com.spark.lola.support.netty.common.NettyCacheUtils;
import com.spark.lola.support.netty.constant.NettyCommands;
import com.spark.lola.support.wms.constant.WmsNettyCommands;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;

/**
 * @Author: DengYeJun
 * @Date: 2020/5/11 18:51
 */
@HawkBean
public class RequestHandler {
    final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    NettyPermissionService nettyPermissionService;

    /**
     * 订阅
     * @param seqId
     * @param body
     * @param ctx
     * @return
     */
    @HawkMethod(cmd = NettyCommands.PUSH_REQUEST,version = NettyCommands.COMMANDS_VERSION)
    public String subscribe(long seqId, byte[] body, ChannelHandlerContext ctx) {
        InetSocketAddress socketAddress = (InetSocketAddress)ctx.channel().remoteAddress();
        String channelId = ctx.channel().id().asLongText();
        String userId = nettyPermissionService.getUserId(channelId);
        logger.info("管理员[{}]push连接建立请求，缓存用户其channel信息，为：[{}]"
                ,userId,channelId);
        NettyCacheUtils.storeChannel(userId, ctx.channel());
        NettyCacheUtils.keyChannelCache.put(ctx.channel(),userId);
        return JSON.toJSONString(ResponseBean.success());
    }


    @HawkMethod(cmd = WmsNettyCommands.PUSH_SUPPLIER_REQUEST,version = NettyCommands.COMMANDS_VERSION)
    public String supplierSubscribe(long seqId, byte[] body, ChannelHandlerContext ctx) {
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        String channelId = ctx.channel().id().asLongText();
        String supplierId = WmsNettyCommands.SUPPLIER_PREFIX + new String(body);
        logger.info("采购商[{}]push连接建立请求，缓存用户其channel信息，为：[{}]"
                , supplierId, channelId);

        NettyCacheUtils.storeChannel(supplierId, ctx.channel());
        NettyCacheUtils.keyChannelCache.put(ctx.channel(), supplierId);
        return JSON.toJSONString(ResponseBean.success());
    }

}
